package service

import (
	"encoding/json"
	"fmt"
	"usplatformserver/internal/model"
	"usplatformserver/pkg/zmq"
)

// 设置报告模板消息请求
type setReportTempMsgReq struct {
	MsgType uint32                    `json:"msgType"`
	Data    *model.ReportTemplateInfo `json:"data"`
}

// 获取报告模板
func (svc *Service) GetReportTemplate(addr string) (*model.ReportTemplateInfo, error) {
	msgStr, err := json.Marshal(zmq.MsgGetReportTemplate)
	if err != nil {
		fmt.Println("json.Marshal failed: ", err)
		return nil, err
	}

	rcvMsg, err := zmq.SendMessage(addr, string(msgStr))
	var rcv *model.ReportTemplateInfo
	err = json.Unmarshal([]byte(rcvMsg), &rcv)
	if err != nil {
		fmt.Println("json.Unmarshal failed: ", err)
		return nil, err
	}

	return rcv, nil
}

// 设置报告模板
func (svc *Service) SetReportTemplate(addr, temp string) error {
	var reportTmp model.ReportTemplateInfo
	//解析输入
	err := json.Unmarshal([]byte(temp), &reportTmp)
	if err != nil {
		fmt.Println("json.Unmarshal(ReportTemplateInfo) failed: ", err)
		return err
	}
	//重组zmq消息
	msgReq := setReportTempMsgReq{
		MsgType: zmq.MsgSetReportTemplate.MsgType,
		Data:    &reportTmp,
	}
	msgReqStr, err := json.Marshal(msgReq)
	if err != nil {
		fmt.Println("json.Marshal(msgReq) failed: ", err)
		return err
	}
	//发送设置阈值消息
	_, err = zmq.SendMessage(addr, string(msgReqStr))
	if err != nil {
		fmt.Println("zmq.SendMessage failed: ", err)
		return err
	}

	return nil
}
